﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace SDLITS.Web
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        ///// <summary>
        ///// 将流中的图片信息放入byte数组后返回该数组
        ///// </summary>
        ///// <param name="stream">文件流</param>
        ///// <param name="context">上下文</param>
        ///// <returns></returns>
        //private byte[] GetImageFromStream(FileStream stream)
        //{
        //    //通过stream得到Image
        //    Image image = Image.FromStream(stream);
        //    //得到一个ms对象
        //    MemoryStream ms = new MemoryStream();
        //    using (ms)
        //    {
        //        //将图片保存至内存流
        //        image.Save(ms, ImageFormat.Jpeg);
        //        byte[] imageBytes = new byte[ms.Length];
        //        ms.Position = 0;
        //        //通过内存流读取到imageBytes
        //        ms.Read(imageBytes, 0, imageBytes.Length);
        //        ms.Close();
        //        //返回imageBytes
        //        return imageBytes;
        //    }
        //}



        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }
        public static void SetGrayscalePalette(Bitmap srcImg)
        {
            // check pixel format
            if (srcImg.PixelFormat != PixelFormat.Format8bppIndexed)
                throw new ArgumentException();
            // get palette
            ColorPalette cp = srcImg.Palette;
            // init palette
            for (int i = 0; i < 256; i++)
            {
                cp.Entries[i] = Color.FromArgb(i, i, i);
            }
            srcImg.Palette = cp;
        }
        ///<summary>
        /// Create and initialize grayscale image
        ///</summary>
        public static Bitmap CreateGrayscaleImage(int width, int height)
        {
            // create new image
            Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            // set palette to grayscale
            SetGrayscalePalette(bmp);
            // return new image
            return bmp;
        }

        public static Bitmap RGB2Gray(Bitmap srcBitmap, byte[] buf)
        {
            int wide = srcBitmap.Width;
            int height = srcBitmap.Height;
            Rectangle rect = new Rectangle(0, 0, wide, height);
            //将Bitmap锁定到系统内存中,获得BitmapData
            BitmapData srcBmData = srcBitmap.LockBits(rect,
                      ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            //创建Bitmap
            Bitmap dstBitmap = CreateGrayscaleImage(wide, height);//这个函数在后面有定义
            BitmapData dstBmData = dstBitmap.LockBits(rect,
                      ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
            //位图中第一个像素数据的地址。它也可以看成是位图中的第一个扫描行
            System.IntPtr srcPtr = srcBmData.Scan0;
            System.IntPtr dstPtr = dstBmData.Scan0;
            //将Bitmap对象的信息存放到byte数组中
            int src_bytes = srcBmData.Stride * height;
            byte[] srcValues = new byte[src_bytes];
            int dst_bytes = dstBmData.Stride * height;
            byte[] dstValues = buf;
            //复制GRB信息到byte数组
            System.Runtime.InteropServices.Marshal.Copy(srcPtr, srcValues, 0, src_bytes);
            System.Runtime.InteropServices.Marshal.Copy(dstPtr, dstValues, 0, dst_bytes);
            //根据Y=0.299*R+0.114*G+0.587B,Y为亮度
            for (int i = 0; i < height; i++)
                for (int j = 0; j < wide; j++)
                {
                    //只处理每行中图像像素数据,舍弃未用空间
                    //注意位图结构中RGB按BGR的顺序存储
                    int k = 3 * j;
                    byte temp = (byte)(srcValues[i * srcBmData.Stride + k + 2] * .299
                         + srcValues[i * srcBmData.Stride + k + 1] * .587
+ srcValues[i * srcBmData.Stride + k] * .114);
                    buf[i * dstBmData.Stride + j] = temp;
                }
            System.Runtime.InteropServices.Marshal.Copy(buf, 0, dstPtr, dst_bytes);
            //解锁位图
            srcBitmap.UnlockBits(srcBmData);
            dstBitmap.UnlockBits(dstBmData);
            return dstBitmap;
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            //Card2.PERSONINFOW info = new Card2.PERSONINFOW();

            ////
            //Card2.OpenCardReader(0, 0x02);
            //Card2.GetPersonMsgW(ref info, MapPath("~/bin/1.bmp"));

            //  Response.Write(Card2.GetBmp(MapPath("~/bin/1.wlt"), 2));

            //Response.Write("<br>");
            //Bitmap b = new Bitmap((MapPath("~/1.bmp")));
            //MemoryStream ms = new MemoryStream();
            //b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            //byte[] bytes = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以，至于区别么，下面有解释
            //ms.Close();
            //foreach (var item in bytes)
            //{
            //    Response.Write(item);
            //}
            //Response.Write("<br>");
            //Response.Write(bytes.Length);
            //Response.Write("<br>");
            //Bitmap b1 = new Bitmap((MapPath("~/finger.bmp")));
            //MemoryStream ms1 = new MemoryStream();
            //b1.Save(ms1, System.Drawing.Imaging.ImageFormat.Bmp);
            //byte[] bytes1 = ms1.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以，至于区别么，下面有解释
            //ms1.Close();
            //foreach (var item in bytes1)
            //{
            //    Response.Write(item);
            //}
            //Response.Write("<br>");
            //Response.Write(bytes1.Length);
            //Response.Write("<br>");

            //Bitmap bm = new Bitmap(256, 304);

            //bm = RGB2Gray(bm, FingerBuf);
            //Response.Write(FingerBuf.Length);
            //Response.Write("<br>");
            //foreach (var item in FingerBuf)
            //{
            //    Response.Write(item);
            //}
            //bm.Save(MapPath("~/1.bmp"));
            //FileStream fstream = File.Open(MapPath("~/1.bmp"), FileMode.Open);
            //fstream.Write(FingerBuf, 0, FingerBuf.Length);
            // while (Finger.IsMxGetImage() != 0)
            // {
            //Finger.mxRaw2Bmp(FingerBuf, FingerBuf1, 256, 304);
            //Response.Write("完成");
            //HttpContext.Current.Response.ClearContent(); //需要输出图象信息 要修改HTTP头 
            //HttpContext.Current.Response.ContentType = "image/BMP";
            //HttpContext.Current.Response.BinaryWrite(FingerBuf);
            //HttpContext.Current.Response.End();
            //string filePath =MapPath("~/1.bmp");   //文件路径
            //FileStream fstream = File.Create(filePath, FingerBuf.Length);
            //try
            //{
            //    fstream.Write(FingerBuf, 0, FingerBuf.Length);   //二进制转换成文件
            //}
            //catch (Exception ex)
            //{
            //    //抛出异常信息
            //    Response.Write(ex.ToString());
            //}
            //finally
            //{
            //    fstream.Close();
            //}
            //  continue;
            //}
            //System.Threading.Thread.Sleep(1000);

            //  Response.Write(Finger.MXLoadFingerFromFile(MapPath("~/Finger.bmp"), FingerBuf));
            // s = Finger.mxUsbGetImage(FingerBuf1, 0);
            //  Finger.mxRaw2Bmp(FingerBuf, FingerBuf1, 256, 304);
            //读入MemoryStream对象
            //MemoryStream memoryStream = new MemoryStream(FingerBuf, 0, FingerBuf.Length);
            ////memoryStream.Write(FingerBuf, 0, FingerBuf.Length);
            ////转成图片
            //Image image = Image.FromStream(memoryStream);

            // ms.Write(FingerBuf, 0, FingerBuf.Length);
            //foreach (var item in FingerBuf)
            //{
            //    Response.Write(item.ToString());
            //}
            // Image image = Image.FromStream(ms);

            //BytesToBitmap(FingerBuf);
            // string n=  Convert.ToBase64String(FingerBuf);
            // Response.Write(n);
            //  System.IO.File.WriteAllBytes(MapPath("~/1.bmp"),FingerBuf);

            // Finger.mxRaw2Bmp(FingerBuf, FingerBuf1, 256, 304);
            // string contenttype = "image/BMP";

            //Response.ContentType = contenttype;
            //Response.Clear();
            //Response.BinaryWrite(FingerBuf);
            //Response.End();
        }



    }
}